package com.micro.platform.oauth.config.oauth.grant;

import com.micro.platform.oauth.framework.OauthManager;
import com.micro.platform.oauth.framework.domain.*;
import com.micro.platform.oauth.framework.exception.OauthException;
import com.micro.platform.oauth.framework.exception.OauthExceptionEnum;
import com.micro.platform.oauth.framework.interfaces.ITokenGranter;
import com.micro.platform.starter.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AuthorizationCodeGranter implements ITokenGranter {
    private String grantType = "authorization_code";
    private OauthManager oauthManager = null;

    public AuthorizationCodeGranter(OauthManager oauthManager) {
        log.info("AuthorizationCodeGranter created!");
        this.oauthManager = oauthManager;
    }

    @Override
    public OauthContext grant(OauthRequest request) {
        String authorizationCode = request.getAuthorization_code();
        if(StringUtils.isEmpty(authorizationCode)){
            throw new OauthException(OauthExceptionEnum.AuthorizationCodeIsNotEmpty);
        }
        String clientId = request.getClientId(),ip = "10.119.8.13";
        AuthorizationCodeDetails authorizationCodeDetails = this.oauthManager.validateAuthorizationCode(clientId, ip, authorizationCode);
        if(null == authorizationCodeDetails){
            throw new OauthException(OauthExceptionEnum.AuthorizationCodeValidateFiled);
        }
        Long userId = authorizationCodeDetails.getUserId();
        ClientDetails clientDetails = this.oauthManager.getClientDetailsService().loadClientDetailsByClientId(request.getClientId());
        if(null == clientDetails){
            throw new OauthException(OauthExceptionEnum.ClientIdIsNotExist);
        }
        UserDetails userDetails = this.oauthManager.getUserDetailsService().loadUserDetailsByAccount(String.valueOf(userId));
        if(null == userDetails){
            throw new OauthException(OauthExceptionEnum.UserIdIsNotExist);
        }
        return new OauthContext(userDetails, request, clientDetails);
    }

    @Override
    public String getGrantType() {
        return grantType;
    }
}
